<?php
    require_once '../model/Stage.php';

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class StageManager {
    private $bdd;
    
    function __construct($bdd) {
        $this->bdd = $bdd;
    }
    
    public function add(Stage $stage) {

        $q = $this->bdd->prepare('INSERT INTO STAGES (idUser, idCat, libelle, url, dateCreation) VALUES(:idUser, :idCat, :libelle, :url, :dateCreation)');
        $q->bindValue(':idUser', $stage->getIdUser());
        $q->bindValue(':idCat', $stage->getIdCategorie());
        $q->bindValue(':libelle', $stage->getLibelle());
        $q->bindValue(':url', $stage->getUrl());
        $q->bindValue(':dateCreation', $stage->getDateCreation());
        $q->execute();
    }

    public function delete($idStage) {
        $this->bdd->exec('DELETE FROM STAGES WHERE idStage='.$idStage);

    }
    
    //liste des stages pour un utilisateur
    public function getListStages($idUser) {
        $listStages = array();
        $req = $this->bdd->prepare('SELECT * FROM STAGES WHERE idUser='.$idUser);
        $req->execute();
        while ($donnees = $req->fetch()) {
            $stage = new Stage($donnees['idStage'], $donnees['idUser'], $donnees['idCat'], $donnees['dateCreation'], $donnees['url'], $donnees['libelle']);
            array_push($listStages, $stage);
        }
        return $listStages;
    }
    
    public function findStage($idStage){   
        //$stage=array();
        $q = $this->bdd->prepare('SELECT * FROM STAGES WHERE idStage= '. $idStage);
        $q->execute();
        $donnees = $q->fetch();
        $newStage = new Stage($donnees['idStage'], $donnees['idUser'], $donnees['idCat'], $donnees['dateCreation'], $donnees['url'], $donnees['libelle']);
        /*while ($donnees = $q->fetch()) {
            $newStage = new Stage($donnees['idStage'], $donnees['idUser'], $donnees['idCat'], $donnees['dateCreation'], $donnees['url'], $donnees['libelle']);
            array_push($stage, $newStage);
        }*/
        return $newStage;
    }
    
    public function getCount ($idUser) {
        $requete ="SELECT COUNT(idStage) FROM STAGES WHERE idUser=$idUser";
        $req = $this->bdd->prepare($requete);
        $req->execute();
        $donnees = $req->fetch();
        $var= $donnees[0];
        //var_dump($donnees);
        return $var;
    }
    
    public function updateStage(stdClass $stage){
        $creation = \date("Y-m-d", strtotime($stage->dateCreation)); 
        $req = $this->bdd->prepare('UPDATE STAGES SET url=:url, dateCreation=:date, libelle=:lib WHERE idStage ='.$stage->idStage);
        $req->execute(array('url' => $stage->URL,'date' => $creation,'lib' => $stage->libelle));
            
     }
}

